package alarm.ruiqi.com.alarm_pro.options.alarm.add;

import android.app.AlertDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.ab.fragment.AbAlertDialogFragment;
import com.ab.task.AbTaskItem;
import com.ab.task.AbTaskListener;
import com.ab.util.AbDialogUtil;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.util.LogUtils;

import java.util.Calendar;
import java.util.HashSet;

import alarm.ruiqi.com.alarm_pro.R;
import alarm.ruiqi.com.alarm_pro.domain.AlarmEntity;
import alarm.ruiqi.com.alarm_pro.options.alarm.UI.AlarmUIHelper;
import alarm.ruiqi.com.alarm_pro.options.base.BaseActivity;
import alarm.ruiqi.com.alarm_pro.service.AlarmServiceImpl;
import alarm.ruiqi.com.alarm_pro.service.MobileApplication;
import alarm.ruiqi.com.alarm_pro.utils.Constant;


public class AddAlarmActivity extends BaseActivity {

    private TimePicker timePicker;
    private CheckedTextView monday, tuesday, wednesday, thursday, friday, saturday, sunday;
    private TextView ringtone, tips;
    private MediaPlayer player;
    private ImageButton playButton;
    private ToggleButton toggleButton;
    private boolean isNew = false;
    private boolean isAdded = false; //是否更新了数据库标志 ，更新错误为false ，此时不自动推出界面

    private AlarmEntity mAlarm;

    private DbUtils mDbUtils;
    private Calendar mCalendar;

    private AlarmServiceImpl mAlarmService;
    private int mInterValDate;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //创建 或者 修改
        mDbUtils = MobileApplication.getInstance().getDefaultDbutils();
        mAlarmService = new AlarmServiceImpl(this);
        setAbContentView(R.layout.activity_add_alarm);

        // 或许当前的年月日，小时，分钟
        mCalendar = Calendar.getInstance();
        mAlarm = (AlarmEntity) getIntent().getSerializableExtra(Constant.GENERAL_SAVE_KEY);
        if (mAlarm == null) {
            //新创建
            mAlarm = new AlarmEntity();
            mAlarm.setAlarmTime(mCalendar.getTimeInMillis());
            isNew = true;

        } else {
            mCalendar.setTimeInMillis(mAlarm.getAlarmTime());
        }
        final int hour = mCalendar.get(Calendar.HOUR_OF_DAY);
        int minute = mCalendar.get(Calendar.MINUTE);

        timePicker = (TimePicker) findViewById(R.id.timePicker);
        timePicker.setIs24HourView(true);
        timePicker.setCurrentMinute(minute);
        timePicker.setCurrentHour(hour);
        timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {

                tips.setText(getAlarmInfo(calculateAlarmTime(timePicker.getCurrentHour(), timePicker.getCurrentMinute())));
            }
        });


        monday = (CheckedTextView) findViewById(R.id.Monday);
        tuesday = (CheckedTextView) findViewById(R.id.Tuesday);
        wednesday = (CheckedTextView) findViewById(R.id.Wednesday);
        thursday = (CheckedTextView) findViewById(R.id.Thursday);
        friday = (CheckedTextView) findViewById(R.id.Friday);
        saturday = (CheckedTextView) findViewById(R.id.Saturday);
        sunday = (CheckedTextView) findViewById(R.id.Sunday);

//

        monday.setOnClickListener(clickListener);
        tuesday.setOnClickListener(clickListener);
        wednesday.setOnClickListener(clickListener);
        thursday.setOnClickListener(clickListener);
        friday.setOnClickListener(clickListener);
        saturday.setOnClickListener(clickListener);
        sunday.setOnClickListener(clickListener);


        playButton = (ImageButton) findViewById(R.id.play);
        playButton.setOnClickListener(clickListener);
        ringtone = (TextView) findViewById(R.id.ringtone);
        ringtone.setOnClickListener(clickListener);
        tips = (TextView) findViewById(R.id.tips);
        findViewById(R.id.save).setOnClickListener(clickListener);
        findViewById(R.id.cancel).setOnClickListener(clickListener);


        HashSet<Integer> repeats = mAlarm.getHashSetRepeats();
        if (repeats.size() > 0) {
            monday.setChecked(repeats.contains(2));
            tuesday.setChecked(repeats.contains(3));
            wednesday.setChecked(repeats.contains(4));
            thursday.setChecked(repeats.contains(5));
            friday.setChecked(repeats.contains(6));
            saturday.setChecked(repeats.contains(7));
            sunday.setChecked(repeats.contains(1));
        }

        toggleButton = (ToggleButton) findViewById(R.id.toggle);
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                timePicker.setAlpha(isChecked ? 1 : 0.5f);
                timePicker.setEnabled(isChecked);
            }
        });

        findViewById(R.id.message).setOnClickListener(clickListener);

        init();

    }


    private void init() {
        if (!mAlarm.isEnable()) {
            tips.setText(getAlarmInfo(null));
        } else {
            tips.setText(getAlarmInfo(mCalendar));
        }
        String uri = mAlarm.getAlarmUri();
        ringtone.setText(TextUtils.isEmpty(uri) ? "请选择铃声" : uri);
        toggleButton.setChecked(mAlarm.isEnable());
    }

    private Calendar calculateAlarmTime(int hourOfDay, int minute) {
        Calendar cal = Calendar.getInstance();
        int calHour = cal.get(Calendar.HOUR_OF_DAY);
        int calMin = cal.get(Calendar.MINUTE);
        cal.set(Calendar.SECOND, 0);
        HashSet<Integer> repeats = getRepeat();
        boolean flag = hourOfDay < calHour || (hourOfDay == calHour && minute < calMin);

        if (repeats.size() == 0) {
            mInterValDate = flag ? 1 : 0;
        } else {
            mInterValDate = mAlarm.getMinInterval(repeats, Calendar.getInstance().get(Calendar.DAY_OF_WEEK), flag);
        }
        cal.add(Calendar.DATE, mInterValDate);
        cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
        cal.set(Calendar.MINUTE, minute);
        return cal;
    }

    private String getAlarmInfo(Calendar cal) {
        if (cal == null) return "请设置闹铃";
        return DateUtils.getRelativeTimeSpanString(cal.getTimeInMillis(), System.currentTimeMillis(),
                DateUtils.SECOND_IN_MILLIS).toString() + "响铃";

    }

    private final View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ringtone:
                    AlarmUIHelper.getInstance().stopMusic(player, playButton);
                    ;
                    Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
                    //设置铃声类型和title
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALARM);
                    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "设置闹铃铃声");
                    //当设置完成之后返回到当前的Activity
                    startActivityForResult(intent, 3);
                    return;
                case R.id.play:
                    if (player != null && player.isPlaying()) {
                        AlarmUIHelper.getInstance().stopMusic(player, playButton);
                    } else {
                        player.release();
                        player = new MediaPlayer();
                        AlarmUIHelper.getInstance().playMusic(AddAlarmActivity.this,player , Uri.parse(mAlarm.getAlarmUri()), playButton);
                    }

                    return;
                case R.id.message:
                    new AlertDialog.Builder(AddAlarmActivity.this)
                            .setIcon(R.drawable.msp_edit_warning)
                            .setTitle("注意")
                            .setMessage(R.string.add_alarm_message_ps)
                            .show();
                    return;
                case R.id.save:
                    if (isNew && !toggleButton.isChecked()) {
                        //未创建时推出保存
                        AbDialogUtil.showAlertDialog(AddAlarmActivity.this, "注意", "闹钟不会被创建,确定要退出吗?", new AbAlertDialogFragment.AbDialogOnClickListener() {
                            @Override
                            public void onPositiveClick() {
                                AbDialogUtil.removeDialog(AddAlarmActivity.this);
                                finish();
                            }

                            @Override
                            public void onNegativeClick() {
                                AbDialogUtil.removeDialog(AddAlarmActivity.this);
                            }
                        });
                    } else {
                        AbDialogUtil.showProgressDialog(AddAlarmActivity.this, R.drawable.rotate_loading_360, getString(R.string.loading));
                        save();
                    }

                    return;
                case R.id.cancel:
                    finish();
                    return;
            }

            checkWeek(v);

        }


    };

    private void checkWeek(View v) {
        CheckedTextView ct = (CheckedTextView) v;
        ct.setChecked(!ct.isChecked());
        tips.setText(getAlarmInfo(calculateAlarmTime(timePicker.getCurrentHour(), timePicker.getCurrentMinute())));

        YoYo.with(Techniques.FlipInX).playOn(ct);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK || requestCode != 3) {
            return;
        }
        try {
            Uri pickedUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); //获取选择的URI
            Toast.makeText(this, pickedUri.toString(), Toast.LENGTH_LONG).show();
            Ringtone selectedRingtone = RingtoneManager.getRingtone(AddAlarmActivity.this, pickedUri);
            String title = selectedRingtone.getTitle(this);

            if (TextUtils.isEmpty(title)) {
                ringtone.setText(pickedUri.toString());
            } else {
                ringtone.setText(title);
            }
            mAlarm.setAlarmUri(pickedUri.toString());
            mAlarm.setAlarmUriTitle(title);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 创建定时器
     */
    private void save() {
        MobileApplication.getInstance().getQueue().execute(new AbTaskItem(new AbTaskListener() {
            @Override
            public void get() {
                LogUtils.i("mAlarm = " + mAlarm);
                calculateAlarmTime(timePicker.getCurrentHour(), timePicker.getCurrentMinute());//默认计算一次
                try {
                    mAlarm.setRepeat_s(getRepeat()); //设置重复
                    mAlarm.setInterValDate(mInterValDate); //设置下个闹钟间隔
                    mAlarm = mAlarmService.checkAlarmBeforeSave(mAlarm, toggleButton.isChecked(), timePicker);
                    if (isNew) {
                        mDbUtils.saveBindingId(mAlarm); //保存数据库
                    } else {
                        mDbUtils.update(mAlarm);
                    }
                    isAdded = true;

                } catch (Exception e) {
                    e.printStackTrace();
                    isAdded = mAlarmService.reSaveAll(mDbUtils, mAlarm, isNew);
                }

            }

            @Override
            public void update() {
                AbDialogUtil.removeDialog(AddAlarmActivity.this);
                if (isAdded) {
                    //结束界面
                    mAlarmService.createAlarm(AddAlarmActivity.this, mAlarm, toggleButton.isChecked());
                    Intent res = getIntent();
                    res.putExtra(Constant.GENERAL_SAVE_KEY, mAlarm);
                    setResult(toggleButton.isChecked() ? 0x2 : 0x3, res);
                    LogUtils.i("update OK! setResult");
                    finish();
                } else {
                    Toast.makeText(AddAlarmActivity.this, "闹铃创建失败", Toast.LENGTH_LONG).show();
                }

            }
        }));

    }

    /**
     * 获取重复周期的hashset
     *
     * @return
     */
    private HashSet<Integer> getRepeat() {
        HashSet<Integer> repeats = new HashSet<>();
        repeats.add(getFlag(monday));
        repeats.add(getFlag(tuesday));
        repeats.add(getFlag(thursday));
        repeats.add(getFlag(wednesday));
        repeats.add(getFlag(friday));
        repeats.add(getFlag(saturday));
        repeats.add(getFlag(sunday));
        repeats.remove(null);//去除null
        return repeats;
    }

    private Integer getFlag(CheckedTextView checkedTextView) {
        if (checkedTextView.isChecked())
            return Integer.parseInt(checkedTextView.getTag().toString());
        return null;
    }

//======================

    @Override
    protected void onStart() {
        super.onStart();
        player = new MediaPlayer();
    }

    @Override
    protected void onStop() {
        super.onStop();
        player.release();
        player = null;
    }
}
